package com.chatplus.application.web.security;

import org.springframework.security.crypto.password.PasswordEncoder;

import java.util.Collection;

/**
 * 组合密码编码器
 * @author weird
 */
public class CombinedPasswordEncoder implements PasswordEncoder {
    /**
     * 编码时使用的密码编码器
     */
    private final PasswordEncoder encodePasswordEncoder;
    /**
     * 只用在解码时使用的密码编码器集合
     */
    private final Collection<CompatiblePasswordEncoder> compatiblePasswordEncoders;

    public CombinedPasswordEncoder(PasswordEncoder encodePasswordEncoder, Collection<CompatiblePasswordEncoder> compatiblePasswordEncoders) {
        this.encodePasswordEncoder = encodePasswordEncoder;
        this.compatiblePasswordEncoders = compatiblePasswordEncoders;
    }

    @Override
    public String encode(CharSequence rawPassword) {
        return encodePasswordEncoder.encode(rawPassword);
    }

    @Override
    public boolean matches(CharSequence rawPassword, String encodedPassword) {
        for (CompatiblePasswordEncoder compatiblePasswordEncoder : compatiblePasswordEncoders) {
            if (compatiblePasswordEncoder.isSupport(encodedPassword)) {
                return compatiblePasswordEncoder.matches(rawPassword, encodedPassword);
            }
        }
        return encodePasswordEncoder.matches(rawPassword, encodedPassword);
    }
}
